<template>
  <div class="search-cantainer">
    <div class="controll">
      <label>搜索:</label>
      <select v-if='searchTypes.length > 1' @input="onInput" @change="onChange" v-model="searchType">
        <option v-for="opt in searchTypes" :value="opt.type">{{opt.label}}</option>
      </select>
      <input v-model='searchValue' @input="onInput" @change="onChange" />
    </div>
</template>
<script>
export default {
  props: {
    types: {
      type: [Array]
    },
    delaySearch: {
      type: Number,
      default: 500
    },
    value: Object
  },
  data: function () {
    return {
      searchType: this.types[0].type || this.types[0],
      searchValue: this.value.value
    }
  },
  computed: {
    searchTypes: function () {
      return this.types.map((t) => {
        if (typeof (t) === 'object') {
          return t
        } else {
          return {
            type: t,
            label: t
          }
        }
      })
    }
  },
  methods: {
    onInput: function () {
      if (this._delaySearchTimeout) {
        clearTimeout(this._delaySearchTimeout)
        this._delaySearchTimeout = null
      }
      this._delaySearchTimeout = setTimeout(() => {
        clearTimeout(this._delaySearchTimeout)
        this._delaySearchTimeout = null
        this.$emit('input', {
          type: this.searchType,
          value: this.searchValue
        })
      }, this.delaySearch)
    },
    onChange: function () {
      this.$emit('change', {
        type: this.searchType,
        value: this.searchValue
      })
    }

  }
}
</script>
<style scoped lang="scss">
.search-cantainer {
  margin-bottom: 10px;
  .controll {
    label {
      padding-left: 10px;
    }
    input {
      display: inline-flex;
      padding: 4px 3px;
    }
  }
}
</style>
